﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 用户关系
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2017.11.07
    /// </summary>
    public class UserRelationBll
    {
        private UserRelationIService service = new UserRelationService();
        private UserIService userService = new UserService();
        /// <summary>
        /// 根据用户主键获取列表
        /// </summary>
        /// <param name="userId">用户主键</param>
        /// <returns></returns>
        public async Task<List<UserRelationEntity>> GetListByUserId(string userId)
        {
            try
            {
                return await service.GetListByUserId(userId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 根据对象主键获取列表
        /// </summary>
        /// <param name="objectId">对象主键</param>
        /// <returns></returns>
        public async Task<List<UserRelationEntity>> GetListByObjectId(string objectId)
        {
            try
            {
                return await service.GetListByObjectId(objectId);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 信息
        /// </summary>
        /// <param name="id">主键值</param>
        /// <returns></returns>
        public async Task<UserRelationEntity> GetInfo(string id)
        {
            try
            {
                return await service.GetInfo(id);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids">主键值</param>
        public async Task Delete(string[] ids)
        {
            try
            {
                await service.Delete(ids);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="objectId">对象主键</param>
        /// <param name="objectType">实体类型</param>
        /// <param name="entitys">实体对象</param>
        public async Task Save(string objectId, string objectType, string[] userIds)
        {
            try
            {
                #region 清空原有数据
                await service.DeleteByObject(new UserRelationEntity() { ObjectId = objectId, ObjectType = objectType });
                #endregion

                var relationList = new List<UserRelationEntity>();
                foreach (var item in userIds)
                {
                    var entity = new UserRelationEntity();
                    entity.Id = CommonHelper.Guid;
                    entity.CreatorTime = DateTime.Now;
                    entity.CreatorUserId = UserProvider.Instance.Get().UserId;
                    entity.ObjectId = objectId;
                    entity.ObjectType = objectType;
                    entity.UserId = item;
                    relationList.Add(entity);
                }
                await service.Create(relationList);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

        /// <summary>
        /// 修改用户岗位id或角色id
        /// </summary>
        /// <param name="oldUserIds"></param>
        /// <param name="newUserIds"></param>
        /// <param name="objectId"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public async Task UpdateUserRelation(List<string> oldUserIds, List<string> newUserIds, string objectId, string objectType)
        {
            var userEntityList = await userService.GetList();
            List<string> intersection = oldUserIds.Intersect(newUserIds).ToList();
            oldUserIds = oldUserIds.Except(intersection).ToList();
            newUserIds = newUserIds.Except(intersection).ToList();
            if (objectType.Equals("Position"))
            {
                foreach (var oldId in oldUserIds)
                {
                    var userEntity = userEntityList.Find(x => x.Id == oldId);
                    userEntity.PositionId = RemoveID(userEntity.PositionId, objectId);
                    await userService.Update(userEntity);
                }
                foreach (var newId in newUserIds)
                {
                    var userEntity = userEntityList.Find(x => x.Id == newId);
                    userEntity.PositionId = AddID(userEntity.PositionId, objectId);
                    await userService.Update(userEntity);
                }
            }
            else if (objectType.Equals("Role"))
            {
                foreach (var oldId in oldUserIds)
                {
                    var userEntity = userEntityList.Find(x => x.Id == oldId);
                    userEntity.RoleId = RemoveID(userEntity.RoleId, objectId);
                    await userService.Update(userEntity);
                }
                foreach (var newId in newUserIds)
                {
                    var userEntity = userEntityList.Find(x => x.Id == newId);
                    userEntity.RoleId = AddID(userEntity.RoleId, objectId);
                    await userService.Update(userEntity);
                }
            }
        }


        /// <summary>
        /// 去除用户岗位或角色id
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="objectId"></param>
        /// <returns></returns>
        private string RemoveID(string ids, string objectId)
        {
            ids = ids.IsEmpty() ? "" : ids;
            var list = new List<string>(ids.Split(","));
            var newList = list.FindAll(x => x != objectId);
            var newIds = string.Join(",", newList).Trim(',');
            return newIds;
        }

        /// <summary>
        /// 添加用户岗位或角色id
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="objectId"></param>
        /// <returns></returns>
        private string AddID(string ids, string objectId)
        {
            ids = ids.IsEmpty() ? "" : ids;
            var list = new List<string>(ids.Split(","));
            list.Add(objectId);
            var newIds = string.Join(",", list).Trim(',');
            return newIds;
        }
    }
}
